package com.atguigu.tingshu.account.consumer;

import com.atguigu.tingshu.account.service.RechargeInfoService;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import lombok.extern.log4j.Log4j2;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/***
 * 充值订单支付成功后接收消息更新充值订单的支付状态
 */
@Component
@Log4j2
public class AccountPaidMessageConsumer {

    @Autowired
    private RechargeInfoService rechargeInfoService;

    /**
     * 接收消息将充值订单状态改为已支付
     * @param channel
     * @param message
     */
    @RabbitListener(queues = "account_order_queue")
    @SneakyThrows
    public void accountPaidMessage(Channel channel, Message message){
        // 获取消息 -- 支付结果
        String resultString = new String(message.getBody());
        MessageProperties messageProperties = message.getMessageProperties();
        long deliveryTag = messageProperties.getDeliveryTag();
        try {
            // 更新充值订单
            rechargeInfoService.updateRechargeInfo(resultString);
            channel.basicAck(deliveryTag,false);
        }catch (Exception e){
            if (messageProperties.getRedelivered()){
                log.error("修改充值订单支付状态失败: " + e.getMessage() + ", 消息报文: " + resultString);
                channel.basicReject(deliveryTag,false);
            }else {
                channel.basicReject(deliveryTag,true);
            }
        }
    }


}